﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Microhard.Core.Net;
using System.ServiceModel.Dispatcher;

namespace Microhard.Core.Map.Baidu
{
    public class BaiduMapHelper
    {
        public static double GetGeoNumber(string encodingValue)
        {
            byte[] xBuffer = Convert.FromBase64String(encodingValue);
            string strX = Encoding.UTF8.GetString(xBuffer, 0, xBuffer.Length);
            return double.Parse(strX);
        }

        public static LocationModel GetBaiduPoint(double gpslng, double gpslat)
        {
            LocationModel result = new LocationModel();
            //http://api.map.baidu.com/ag/coord/convert?from=2&to=4&mode=1&x=116.3786889372559&y=39.90762965106183
            string convertUrl = "http://api.map.baidu.com/ag/coord/convert?from=2&to=4&mode=1&x={0}&y={1}";
            string finUrl = string.Format(convertUrl, gpslng, gpslat);
            string html = HttpReader.HttpGet(finUrl);
            JsonQueryStringConverter jqsv = new JsonQueryStringConverter();
            try
            {
                var rl = (ConvertLocationResult[])jqsv.ConvertStringToValue(html, typeof(ConvertLocationResult[]));
                if (rl != null && rl.Length > 0)
                {
                    if (rl.First().error == "0")
                    {
                        var lt = rl.First();
                        result.Lng = GetGeoNumber(lt.x);
                        result.Lat = GetGeoNumber(lt.y);
                    }
                }

            }
            catch (Exception ex)
            {
                Log.Error("GetBaiduPoint", ex);
            }
            return result;
        }
    }
}
